<?php
class User extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		$this->load->model('Util');
		$this->load->model('UserManager');
		$this->load->model('DatabaseManager');
		$this->load->model('SessionManager');
		$this->load->helper(array('form', 'url'));
	}
	public function updateUser(){
		$username=$_REQUEST['username'];
		$sessionId=$_REQUEST['sessionId'];
		$data=$this->UserManager->update_user($username,$sessionId);
		echo json_encode($data);
	}
	public function uploadAvatar()
	{
		$username=$_REQUEST['username'];
		$name=$_REQUEST['name'];
		$sessionId=$_REQUEST['sessionId'];
		$host=$_REQUEST['host'];
		$fileType=$_REQUEST['fileType'];
		if(!$this->SessionManager->check($username,$sessionId)){
			echo json_encode($this->Util->format_return(0,6,'wrong session'));
			return;
		}
		$icoPath='/uploads/avatar/';
		$config['upload_path']='.'.$icoPath;
		$config['allowed_types']='*';
		$config['file_ext_tolower']=true;
		$config['overwrite']=true;
		$config['file_name']='userAvatar_'.$username.'_'.time().$fileType;
		$this->load->library('upload', $config);
		if ( ! $this->upload->do_upload('userfile'))
		{
			$error = array('error' => $this->upload->display_errors());
			echo json_encode($this->Util->format_return(0,7,'upload failed',$error));
		}
		else
		{
			$data=$this->upload->data('file_name');
			$ico=$host.$icoPath.$data;
			$this->DatabaseManager->save_avatar($username,$name,$ico);
			echo json_encode($this->Util->format_return(1,1,'success',$ico));
		}
	}
	public function getUserInfoByUsername(){
		$user=$_REQUEST['user'];
		$username=$_REQUEST['username'];
		$sessionId=$_REQUEST['sessionId'];
		$data=$this->UserManager->get_userinfo_by_username($user,$username,$sessionId);
		echo json_encode($data);
	}
	public function getIntegralDetail(){
		$username=$_REQUEST['username'];
		$sessionId=$_REQUEST['sessionId'];
		$data=$this->UserManager->get_integral_detail($username,$sessionId);
		echo json_encode($data);
	}
	public function signIn(){
		$username=$_REQUEST['username'];
		$sessionId=$_REQUEST['sessionId'];
		$time=$_REQUEST['timestamp'];
		$data=$this->UserManager->sign_in($username,$sessionId,$time);
		echo json_encode($data);
	}
	public function checkPhone(){
		$phone=$_REQUEST['phone'];
		$data=$this->UserManager->check_phone($phone);
		echo json_encode($data);
	}
	public function getFriendsList(){
		$username=$_REQUEST['username'];
		$sessionId=$_REQUEST['sessionId'];
		$data=$this->UserManager->get_friends_list($username,$sessionId);
		echo json_encode($data);
	}
	public function test(){
		$this->DatabaseManager->add_integral('12946137',3);
	}
}